//
//  BSBigPictureViewController.m
//  Baisijie
//
//  Created by 王建伟 on 2017/3/29.
//  Copyright © 2017年 RangGuangyu. All rights reserved.
//

#import "BSBigPictureViewController.h"
#import <UIImageView+WebCache.h>
#import "BSGifItem.h"
#import "BSImageItem.h"
#import "BSDownloadImageTool.h"
#import "BSProgressView.h"
#import <StoreKit/StoreKit.h>
#import <Photos/Photos.h>
#import <CTAssetsPickerController.h>

@interface BSBigPictureViewController ()<UIScrollViewDelegate,CTAssetsPickerControllerDelegate>

@property (weak, nonatomic) IBOutlet BSProgressView *progressView;

/** 滚动视图 */
@property (nonatomic ,weak) UIScrollView *scrollView;
/** 图片视图 */
@property (nonatomic ,weak) UIImageView *imageView;
/** 图片的地址 */
@property (nonatomic ,copy) NSString *imageUrlStr;


- (PHAssetCollection *)assetCollection;
- (PHFetchResult<PHAsset *> *)createdAssets;

@end

@implementation BSBigPictureViewController

- (UIImageView *)imageView {
    if (!_imageView) {
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, KScreenW, KScreenH)];
        [self.scrollView addSubview:imageView];
        imageView.userInteractionEnabled = YES;
        [imageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(backBtnClick)]];
        _imageView = imageView;
    }
    return _imageView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupScrollView];
    [self setupImageView];
}
- (void)setupScrollView {
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    scrollView.backgroundColor = [UIColor blackColor];
    scrollView.alwaysBounceVertical = YES;
    scrollView.maximumZoomScale = 3.0;
    scrollView.delegate = self;
    scrollView.showsHorizontalScrollIndicator = NO;
    [self.view insertSubview:scrollView atIndex:0];
    _scrollView = scrollView;
}
- (void)setupImageView {
    NSString *bigImageUrl = self.isGifImage ? _gif.images.firstObject : _image.big.firstObject;
    _imageUrlStr = bigImageUrl;
    CGFloat imageViewH = self.isGifImage ? (KScreenW * _gif.height / _gif.width) : (KScreenW * _image.height / _image.width);
    //NSString *thumbnailImageUrl = self.isGifImage ? self.gif.gif_thumbnail.firstObject : self.image.thumbnail_small.firstObject;
    
    self.imageView.bs_height = imageViewH;
    if (imageViewH < KScreenH) {
        self.imageView.bs_centerY = KScreenH * 0.5;
    }
    self.scrollView.contentSize = CGSizeMake(0, imageViewH);
    _progressView.progress = 0.0;
    _progressView.hidden = NO;
    [self.imageView sd_setImageWithURL:[NSURL URLWithString:bigImageUrl] placeholderImage:nil options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize) {
        _progressView.progress = receivedSize * 1.0 / expectedSize;
    } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        _progressView.hidden = YES;
    }];
}
- (IBAction)backBtnClick {
    [self dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - 获取app的相册
- (PHAssetCollection *)assetCollection {
    //取出手机中的自定义相册
    PHFetchResult<PHAssetCollection *> *assetCollections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    for (PHAssetCollection *assetCollection in assetCollections) {
        if ([assetCollection.localizedTitle isEqualToString:BSBundleDisplayName]) {
            return assetCollection;
        }
    }
    __block NSString *createIdentifier = nil;
    NSError *error = nil;
    [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
        // 获取创建的相册的id
        createIdentifier = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:BSBundleDisplayName].placeholderForCreatedAssetCollection.localIdentifier;
    } error:&error];
    if (error) return nil;
    // 根据相册id找到对应的相册
    return [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[createIdentifier] options:nil].firstObject;
}
- (PHFetchResult<PHAsset *> *)createdAssets {
    //把相片保存到图片库
    __block NSString *placeholderID = nil;
    NSError *error = nil;
    [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
        placeholderID = [PHAssetChangeRequest creationRequestForAssetFromImage:self.imageView.image].placeholderForCreatedAsset.localIdentifier;
    } error:&error];
    if (error) {
        return nil;
    }
    return [PHAsset fetchAssetsWithLocalIdentifiers:@[placeholderID] options:nil];
}
- (IBAction)saveBtnClick {
    [self visitPhotoGalleryWithSave:YES];
}

/**
 访问照片

 @param isSave 是否为保存图片（1、保存图片 0、选择图片）
 */
- (void)visitPhotoGalleryWithSave:(BOOL)isSave {
    PHAuthorizationStatus oldStatus = [PHPhotoLibrary authorizationStatus];
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
        dispatch_async(dispatch_get_main_queue(), ^{
            switch (status) {
                case PHAuthorizationStatusNotDetermined: {
                    // 不确定当前app是否可以访问相册
                }
                    break;
                case PHAuthorizationStatusRestricted: {
                    // 无法访问相册
                    [SVProgressHUD showErrorWithStatus:@"无法访问相册"];
                }
                    break;
                case PHAuthorizationStatusDenied: {
                    if (oldStatus == PHAuthorizationStatusNotDetermined) break;
                    // 用户拒绝当前app访问相册
                    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"无法保存" message:[NSString stringWithFormat:@"请在iPhone的\"设置\"->\"隐私\"->\"照片\"选项中，允许【%@】访问你的照片。",BSBundleDisplayName] preferredStyle:UIAlertControllerStyleAlert];
                    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                        
                    }];
                    [alert addAction:cancel];
                    UIAlertAction *open = [UIAlertAction actionWithTitle:@"开启" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                        if ([[UIApplication sharedApplication] canOpenURL:url]) {
                            [[UIApplication sharedApplication] openURL:url];
                        }
                    }];
                    [alert addAction:open];
                    [self presentViewController:alert animated:YES completion:nil];
                }
                    break;
                case PHAuthorizationStatusAuthorized: {
                    // 用户运行当前app访问相册
                    if (isSave) {
                        //保存图片
                        [self saveImageIntoAlum];
                    } else {
                        //选择图片
                        [self selectImages];
                    }
                }
                    break;
                    
                default:
                    break;
            }
        });
    }];
}
#pragma mark - 保存图片到相册
- (void)saveImageIntoAlum {
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
    [SVProgressHUD setMinimumDismissTimeInterval:1.5];
    BOOL isSaved = [BSUserDefaults boolForKey:_imageUrlStr];
    if (isSaved) {
        [SVProgressHUD showErrorWithStatus:@"图片已保存"];
        return;
    }
    [SVProgressHUD showWithStatus:@"保存中..."];
    //把相片保存到图片库
    __block PHFetchResult<PHAsset *> *createdAssets = self.createdAssets;
    if (createdAssets == nil) {
        [SVProgressHUD showErrorWithStatus:@"保存失败!"];
        return;
    }
    //获取本程序的图片库
    PHAssetCollection *createdCollection = self.assetCollection;
    if (createdCollection == nil) {
        [SVProgressHUD showErrorWithStatus:@"创建相册失败!"];
        return;
    }
    //把图片保存到本程序的自定义相册中
    NSError *error = nil;
    [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
        PHAssetCollectionChangeRequest *request = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:createdCollection];
        [request insertAssets:createdAssets atIndexes:[NSIndexSet indexSetWithIndex:0]];
    } error:&error];
    if (error) {
        [SVProgressHUD showErrorWithStatus:@"保存失败!"];
    } else {
        [BSUserDefaults setBool:YES forKey:_imageUrlStr];
        [BSUserDefaults synchronize];
        [SVProgressHUD showSuccessWithStatus:@"保存成功!"];
    }
    //保存图片到相册的三种方法
    /*
    // 1
    UIImageWriteToSavedPhotosAlbum(self.imageView.image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);

    // 2
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        [PHAssetChangeRequest creationRequestForAssetFromImage:self.imageView.image];
    } completionHandler:^(BOOL success, NSError * _Nullable error) {
        if (error) {
            [SVProgressHUD showErrorWithStatus:@"保存失败!"];
        } else {
            [SVProgressHUD showSuccessWithStatus:@"保存成功!"];
        }
    }];

    // 3
    NSError *error = nil;
    [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
        [PHAssetChangeRequest creationRequestForAssetFromImage:self.imageView.image];
    } error:&error];
    if (error) {
        [SVProgressHUD showErrorWithStatus:@"保存失败!"];
    } else {
        [SVProgressHUD showSuccessWithStatus:@"保存成功!"];
    }
    */
}
#pragma mark - 选择图片
- (void)selectImages {
    CTAssetsPickerController *vc = [[CTAssetsPickerController alloc] init];
    vc.delegate = self;
    vc.defaultAssetCollection = PHAssetCollectionSubtypeSmartAlbumUserLibrary;
    vc.assetCollectionSubtypes = @[@(PHAssetCollectionSubtypeSmartAlbumUserLibrary),@(PHAssetCollectionSubtypeAlbumRegular)];
    vc.showsEmptyAlbums = NO;
    vc.showsCancelButton = YES;
    vc.showsSelectionIndex = YES;
    [self presentViewController:vc animated:YES completion:nil];
}
#pragma mark - <CTAssetsPickerControllerDelegate>
- (BOOL)assetsPickerController:(CTAssetsPickerController *)picker shouldSelectAsset:(PHAsset *)asset {
    NSInteger maxCount = 9;
    if (picker.selectedAssets.count < maxCount) {
        return YES;
    }
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:[NSString stringWithFormat:@"最多可选择%zd张照片",maxCount] message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:cancel];
    [picker presentViewController:alert animated:YES completion:nil];
    return NO;
}
- (void)assetsPickerController:(CTAssetsPickerController *)picker didFinishPickingAssets:(NSArray *)assets {
    [picker dismissViewControllerAnimated:YES completion:^{
        PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
        options.synchronous = YES;
        options.version = PHImageRequestOptionsVersionOriginal;
        for (PHAsset *asset in assets) {
            [[PHImageManager defaultManager] requestImageForAsset:asset targetSize:CGSizeMake(asset.pixelWidth, asset.pixelHeight) contentMode:PHImageContentModeDefault options:options resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
                
            }];
        }
    }];
}
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    if (error) {
        [SVProgressHUD showErrorWithStatus:@"保存失败!"];
    } else {
        [SVProgressHUD showSuccessWithStatus:@"保存成功!"];
    }
}
- (IBAction)forwardBtnClick {
    [self visitPhotoGalleryWithSave:NO];
}
- (IBAction)writeCommentBtnClick {
    
    [SKStoreReviewController requestReview];
}
#pragma mark - <UIScrollViewDelegate>
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    return self.imageView;
}
- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale {
    CGFloat imageViewH = self.imageView.bs_height * scale;
    if (imageViewH < KScreenH) {
        self.imageView.bs_centerY = KScreenH * 0.5;
    } else {
        self.imageView.bs_y = 0;
    }
}


@end
